package com.shelpe.services.algorithm.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.shelpe.services.algorithm.client.RankClient;
import com.shelpe.services.algorithm.entity.batis.Keyword;
import com.shelpe.services.algorithm.entity.mongo.KeywordRealtimeRankSyncLog;
import com.shelpe.services.algorithm.repository.mongo.KeywordRealtimeRankSyncLogRepository;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class RealtimeRankService {

	@Autowired
	private RankClient rankClient;
	@Autowired
	private KeywordRealtimeRankSyncLogRepository keywordRealtimeRankSyncLogRepository;
	
	public List<RankClient.KeywordRealtimeRankItem> syncRanks(String nick, long adgroupID, List<Long> keywordIDs){
		List<RankClient.KeywordRealtimeRankItem> ranks = new ArrayList<RankClient.KeywordRealtimeRankItem>();
		
		KeywordRealtimeRankSyncLog syncLog = new KeywordRealtimeRankSyncLog();
		syncLog.setAdgroupID(adgroupID);
		syncLog.setupID(adgroupID, new Date());
		syncLog.setSyncTime(new Date());
		while(keywordIDs.size() > 0){
			List<Long> toFindKeywordIDs = new ArrayList<Long>();
			if(keywordIDs.size() > 20){
				toFindKeywordIDs.addAll(keywordIDs.subList(0, 20));
				keywordIDs = keywordIDs.subList(20, keywordIDs.size());
			}else{
				toFindKeywordIDs.addAll(keywordIDs.subList(0, keywordIDs.size()));
				keywordIDs.clear();
			}
			RankClient.KeywordRealtimeRankItemResponse res = this.rankClient.findRealtimeRanks(nick, adgroupID, toFindKeywordIDs.toArray(RankClient.TEMPLATE));
			if(res != null && res.getRes() != null && res.getRes().getResult() != null && res.getRes().getResult().getDataList() != null
					&& res.getRes().getResult().getDataList().getItems() != null){
				for(RankClient.KeywordRealtimeRankItem rank: res.getRes().getResult().getDataList().getItems()){
					log.debug("realtime rank: {}", rank);
					ranks.add(rank);
					KeywordRealtimeRankSyncLog.KeywordRankItem item = new KeywordRealtimeRankSyncLog.KeywordRankItem();
					item.setKeywordID(rank.getKeywordID());
					item.setRank(rank);
//					item.setWord(item.getWord());
					syncLog.addItem(item);
				}
			}else{
				log.error("fail to findRealtimeRanks: {}, error: {}", adgroupID, res!=null?res.getError():"unknown");
			}
		}
		this.keywordRealtimeRankSyncLogRepository.save(syncLog);
		
		return ranks;
	}
	
}
